package org.pine.start.interceptor;

import cn.hutool.core.collection.CollUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.pine.common.beans.OperateLogBody;
import org.pine.common.components.OperateLogContext;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;
import java.util.Objects;

/**
 * 操作日志拦截器
 *
 * @author pine
 * @version v1.0
 * @since 2025-04-28 21:50
 */
@Slf4j
public class OperateLogHandlerInterceptor implements HandlerInterceptor {

    private final List<OperateLogHandler> operateLogHandlers;

    public OperateLogHandlerInterceptor(List<OperateLogHandler> operateLogHandlers) {
        Objects.requireNonNull(operateLogHandlers);
        this.operateLogHandlers = operateLogHandlers;
    }


    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        if (ex == null) {
            List<OperateLogBody> operateLogBodies = OperateLogContext.get();
            if (CollUtil.isNotEmpty(operateLogBodies)) {
                for (OperateLogBody operateLogBody : operateLogBodies) {
                    try {
                        for (OperateLogHandler operateLogHandler : operateLogHandlers) {
                            operateLogHandler.handle(operateLogBody);
                        }
                    } catch (Exception e) {
                        log.error("operateLogHandler error. operate log content={}", operateLogBody);
                    }
                }
            }
        }
    }
}
